#!/bin/bash

echo "======================================"
echo "     IAS应用平台启动脚本"
echo "======================================"

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "错误: Docker 未安装，请先安装 Docker"
    exit 1
fi

# 检查Docker Compose是否安装
if ! command -v docker-compose &> /dev/null; then
    echo "错误: Docker Compose 未安装，请先安装 Docker Compose"
    exit 1
fi

# 创建必要的目录
echo "创建必要的目录..."
mkdir -p docker/rocketmq
mkdir -p logs

# 创建RocketMQ Broker配置文件
echo "创建RocketMQ配置文件..."
cat > docker/rocketmq/broker.conf << EOF
brokerClusterName = DefaultCluster
brokerName = broker-a
brokerId = 0
deleteWhen = 04
fileReservedTime = 48
brokerRole = ASYNC_MASTER
flushDiskType = ASYNC_FLUSH
brokerIP1 = rocketmq-broker
EOF

# 编译项目
echo "编译项目..."
mvn clean package -DskipTests

if [ $? -ne 0 ]; then
    echo "错误: 项目编译失败"
    exit 1
fi

# 启动基础设施
echo "启动基础设施..."
docker-compose up -d mysql redis nacos rocketmq-nameserver rocketmq-broker rocketmq-console

# 等待基础设施启动完成
echo "等待基础设施启动完成..."
sleep 30

# 检查Nacos是否启动成功
echo "检查Nacos服务状态..."
for i in {1..30}; do
    if curl -f http://localhost:8848/nacos/v1/console/health/readiness &> /dev/null; then
        echo "Nacos启动成功"
        break
    fi
    echo "等待Nacos启动... ($i/30)"
    sleep 5
done

# 启动应用服务
echo "启动应用服务..."
docker-compose up -d api-gateway user-service

echo "======================================"
echo "系统启动完成！"
echo "======================================"
echo "服务访问地址："
echo "- API网关: http://localhost:8080"
echo "- Nacos控制台: http://localhost:8848/nacos"
echo "- RocketMQ控制台: http://localhost:8076"
echo "- 用户服务: http://localhost:8001"
echo ""
echo "默认账号："
echo "- 用户名: admin"
echo "- 密码: 123456"
echo "======================================" 